const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const jwtKoa = require('koa-jwt')
const session = require('koa-generic-session')
const redisStore = require('koa-redis')
const { SESSION_SECRET_KEY } = require('./config/scretKeys')
const { REDIS_CONF } = require('./config/db')



//路由注册
const {SECRET} = require('./config/constant')
const index = require('./routes/index')
const users = require('./routes/users')
const userAPIRouter = require('./routes/api/user')



// error handler
onerror(app)
//jwt
app.use(
    jwtKoa({
      secret:SECRET
    }).unless({
      path:[/^\/api\/user\/login/]
    })
)
// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
//app.use(require('koa-static')(__dirname + '/public'))
//对模版进行注册，进行视图渲染
app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

//session配置

app.keys = SESSION_SECRET_KEY
app.use(
    session({
        // cookie的name 默认是 koa.sid
        key: 'sina.sid',
        // redis key 的前缀 默认是 koa.sess
        prefix: 'sinas:sess:',
        cookie: {
            path: '/',
            httpOnly: true,
            maxAge: 24 * 60 * 60 * 1000
        },
        store: redisStore({
            all: `${REDIS_CONF.host}:${REDIS_CONF.port}`
        })
    })
)



// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(userAPIRouter.routes(), userAPIRouter.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
